import { Injectable, Logger } from '@nestjs/common';
import { BaseAdapter } from './base.adapter';
import { 
  ApiProvider, 
  TargetProvider, 
  GenericRequest, 
  GenericResponse,
  GenericMessage,
  HealthStatus,
  TokenManager 
} from '../interfaces/api-adapter.interface';
import { TokenManagerService } from '../services/token-manager.service';
import { 
  GeminiGenerateContentRequest,
  GeminiGenerateContentResponse,
  GeminiCountTokensRequest,
  GeminiCountTokensResponse,
  GeminiContent,
  GeminiPart,
  GeminiRole
} from '../dto/gemini.dto';

/**
 * Gemini to GitHub Copilot API Adapter
 * 将 Gemini API 请求转换为 Copilot 兼容的格式
 */
@Injectable()
export class GeminiCopilotAdapter extends BaseAdapter {
  protected readonly logger = new Logger(GeminiCopilotAdapter.name);

  constructor(private readonly tokenManager: TokenManagerService) {
    super(ApiProvider.GEMINI, TargetProvider.COPILOT);
  }

  /**
   * 将 Gemini 请求转换为通用格式
   */
  async transformRequest(request: any): Promise<GenericRequest> {
    this.logger.debug('Transforming Gemini request to generic format');
    
    // 处理不同的 Gemini API 端点
    if (request.contents) {
      // generateContent 请求
      return this.transformGenerateContentRequest(request as GeminiGenerateContentRequest & { model: string });
    } else if (request.input) {
      // 其他类型的请求（如embeddings）
      return this.transformOtherRequest(request);
    }
    
    throw new Error('Unsupported Gemini request format');
  }

  /**
   * 转换 Gemini generateContent 请求
   */
  private transformGenerateContentRequest(request: GeminiGenerateContentRequest & { model: string }): GenericRequest {
    // 将 Gemini 的 contents 转换为类似 OpenAI 的 messages 格式
    const messages = this.convertGeminiContentsToMessages(request.contents);
    
    // 构建通用请求格式
    const genericRequest: GenericRequest = {
      model: request.model || 'gemini-pro',
      messages: messages,
      temperature: request.generationConfig?.temperature,
      max_tokens: request.generationConfig?.maxOutputTokens,
      top_p: request.generationConfig?.topP,
      stream: false, // 根据端点决定
      metadata: {
        gemini: {
          safetySettings: request.safetySettings,
          tools: request.tools,
          systemInstruction: request.systemInstruction,
          generationConfig: request.generationConfig,
          stopSequences: request.generationConfig?.stopSequences
        }
      }
    };

    return genericRequest;
  }

  /**
   * 转换其他类型的请求
   */
  private transformOtherRequest(request: any): GenericRequest {
    return {
      model: request.model || 'gemini-pro',
      messages: [{ role: 'user', content: request.input || JSON.stringify(request) }],
      metadata: {
        gemini: request
      }
    };
  }

  /**
   * 将 Gemini Contents 转换为标准 messages 格式
   */
  private convertGeminiContentsToMessages(contents: GeminiContent[]): GenericMessage[] {
    return contents.map(content => {
      // 合并所有 parts 的文本内容
      const textContent = content.parts
        .filter((part: GeminiPart) => part.text)
        .map((part: GeminiPart) => part.text)
        .join('\n');
      
      // 转换角色映射
      let role: 'user' | 'assistant' | 'system' = 'user';
      if (content.role === GeminiRole.MODEL) {
        role = 'assistant';
      } else if (content.role === GeminiRole.USER) {
        role = 'user';
      }
      
      return {
        role,
        content: textContent || JSON.stringify(content.parts)
      };
    });
  }

  /**
   * 将通用响应转换为 Gemini 格式
   */
  async transformResponse(response: GenericResponse, originalRequest: any): Promise<any> {
    this.logger.debug('Transforming generic response to Gemini format');
    
    // 根据原始请求类型决定响应格式
    if (originalRequest.contents) {
      return this.transformToGeminiGenerateResponse(response, originalRequest);
    } else if (originalRequest.input) {
      return this.transformToOtherGeminiResponse(response, originalRequest);
    }
    
    return response;
  }

  /**
   * 转换为 Gemini generateContent 响应格式
   */
  private transformToGeminiGenerateResponse(response: GenericResponse, originalRequest: any): GeminiGenerateContentResponse {
    if (!response.content || response.content.length === 0) {
      throw new Error('No valid response content found');
    }

    // 从content中提取文本
    const textContent = response.content
      .filter(block => block.type === 'text')
      .map(block => block.text)
      .join('\n') || 'No content generated';

    // 构建 Gemini 格式的响应
    const geminiResponse: GeminiGenerateContentResponse = {
      candidates: [
        {
          content: {
            parts: [
              {
                text: textContent
              }
            ],
            role: GeminiRole.MODEL
          },
          finishReason: this.mapFinishReason(response.stop_reason),
          index: 0,
          safetyRatings: [] // 安全评级，可以根据需要添加
        }
      ],
      usageMetadata: response.usage ? {
        promptTokenCount: response.usage.input_tokens || 0,
        candidatesTokenCount: response.usage.output_tokens || 0,
        totalTokenCount: response.usage.total_tokens || 0
      } : undefined
    };

    return geminiResponse;
  }

  /**
   * 转换其他类型的响应
   */
  private transformToOtherGeminiResponse(response: GenericResponse, originalRequest: any): any {
    // 对于 countTokens 等请求的处理
    if (originalRequest.endpoint === 'countTokens') {
      return {
        totalTokens: response.usage?.total_tokens || 0
      } as GeminiCountTokensResponse;
    }
    
    return response;
  }

  /**
   * 映射结束原因
   */
  private mapFinishReason(reason?: string): any {
    const reasonMap: Record<string, string> = {
      'stop': 'STOP',
      'length': 'MAX_TOKENS',
      'content_filter': 'SAFETY',
      'function_call': 'OTHER',
      'tool_calls': 'OTHER'
    };
    
    return reasonMap[reason || 'stop'] || 'STOP';
  }

  /**
   * 验证 Gemini 请求
   */
  async validateRequest(request: any): Promise<boolean> {
    try {
      // 检查是否是有效的 Gemini 请求
      if (request.contents && Array.isArray(request.contents)) {
        // generateContent 请求验证
        return request.contents.every((content: any) => 
          content.parts && Array.isArray(content.parts)
        );
      }
      
      if (request.input) {
        // 其他类型请求验证
        return true;
      }
      
      return false;
    } catch (error) {
      this.logger.error(`Gemini request validation failed: ${error.message}`);
      return false;
    }
  }

  /**
   * 获取适配器健康状态
   */
  async getHealthStatus(): Promise<{ healthy: boolean; details: any }> {
    try {
      const tokenStatus = await this.tokenManager.isTokenValid();
      
      return {
        healthy: tokenStatus,
        details: {
          provider: this.provider,
          target: this.target,
          tokenValid: tokenStatus,
          supportedEndpoints: [
            'generateContent',
            'streamGenerateContent', 
            'countTokens',
            'batchEmbedContents'
          ],
          lastHealthCheck: new Date().toISOString()
        }
      };
    } catch (error) {
      this.logger.error(`Gemini adapter health check failed: ${error.message}`);
      return {
        healthy: false,
        details: {
          error: error.message,
          timestamp: new Date().toISOString()
        }
      };
    }
  }

  /**
   * 获取支持的模型列表
   */
  getSupportedModels(): string[] {
    return [
      'gemini-pro',
      'gemini-pro-vision',
      'gemini-1.5-pro',
      'gemini-1.5-flash',
      'gemini-1.5-flash-8b'
    ];
  }

  /**
   * 获取适配器元数据
   */
  getAdapterMetadata(): any {
    return {
      name: 'Gemini to Copilot Adapter',
      version: '1.0.0',
      description: 'Converts Google Gemini API requests to GitHub Copilot compatible format',
      supportedFeatures: [
        'text generation',
        'multi-turn conversations',
        'safety settings',
        'token counting',
        'streaming (basic)',
        'function calling (limited)'
      ],
      limitations: [
        'Some Gemini-specific features may not be fully supported',
        'Advanced safety settings mapping may be approximate',
        'Tool calling support is limited'
      ]
    };
  }

  /**
   * 实现 ApiAdapter 接口 - 将源API转换为通用格式
   */
  async convertToGeneric(sourceRequest: any): Promise<GenericRequest> {
    return this.transformRequest(sourceRequest);
  }

  /**
   * 实现 ApiAdapter 接口 - 将通用格式转换为目标API格式
   */
  async convertFromGeneric(genericRequest: GenericRequest): Promise<any> {
    // 将通用格式转换为 Copilot 格式
    return {
      model: genericRequest.model,
      messages: genericRequest.messages,
      temperature: genericRequest.temperature,
      max_tokens: genericRequest.max_tokens,
      top_p: genericRequest.top_p,
      stream: genericRequest.stream || false
    };
  }

  /**
   * 实现 ApiAdapter 接口 - 解析目标API响应为通用格式
   */
  async parseTargetResponse(targetResponse: any, originalRequest?: any): Promise<GenericResponse> {
    // 将 Copilot 响应转换为通用格式
    const choice = targetResponse.choices?.[0];
    if (!choice) {
      throw new Error('No valid response choice found');
    }

    return {
      id: targetResponse.id || this.generateRequestId(),
      model: targetResponse.model || 'gemini-pro',
      content: [
        {
          type: 'text',
          text: choice.message?.content || choice.text || 'No content generated'
        }
      ],
      stop_reason: this.mapStopReason(choice.finish_reason || 'stop'),
      usage: {
        input_tokens: targetResponse.usage?.prompt_tokens || 0,
        output_tokens: targetResponse.usage?.completion_tokens || 0,
        total_tokens: targetResponse.usage?.total_tokens || 0
      }
    };
  }

  /**
   * 实现 ApiAdapter 接口 - 将通用响应转换为源API格式
   */
  async convertToSourceResponse(genericResponse: GenericResponse, originalRequest?: any): Promise<any> {
    return this.transformResponse(genericResponse, originalRequest);
  }

  /**
   * 实现 ApiAdapter 接口 - 获取请求头部
   */
  async getRequestHeaders(config: any): Promise<Record<string, string>> {
    const token = await this.tokenManager.getValidToken();
    
    return {
      'authorization': `Bearer ${token}`,
      'content-type': 'application/json',
      'user-agent': config.userAgent || 'GeminiToCopilotAdapter/1.0.0',
      'x-request-id': this.generateRequestId()
    };
  }

  /**
   * 实现 ApiAdapter 接口 - 获取目标API端点
   */
  getTargetEndpoint(operation: string): string {
    const endpointMap: Record<string, string> = {
      'chat/completions': '/chat/completions',
      'completions': '/completions',
      'models': '/models',
      'health': '/health'
    };
    
    return endpointMap[operation] || '/chat/completions';
  }

  /**
   * 实现 ApiAdapter 接口 - 健康检查
   */
  async checkHealth(): Promise<HealthStatus> {
    try {
      const tokenValid = await this.tokenManager.isTokenValid();
      
      return {
        status: tokenValid ? 'healthy' : 'degraded',
        provider: this.provider,
        target: this.target,
        details: {
          tokenValid,
          supportedModels: this.getSupportedModels(),
          lastHealthCheck: new Date().toISOString()
        },
        lastCheck: new Date()
      };
    } catch (error) {
      this.logger.error(`Health check failed: ${error.message}`);
      return {
        status: 'unhealthy',
        provider: this.provider,
        target: this.target,
        details: {
          error: error.message,
          timestamp: new Date().toISOString()
        },
        lastCheck: new Date()
      };
    }
  }

  /**
   * 实现 ApiAdapter 接口 - 获取Token管理器
   */
  getTokenManager(): TokenManager {
    return this.tokenManager as TokenManager;
  }
}